package ar.com.lemil.bb.http.commands;

import java.util.Enumeration;
import java.util.Hashtable;

import ar.com.lemil.bb.http.HttpMultipartRequestUtils;
import ar.com.lemil.bb.http.HttpRequestUtils;
import ar.com.lemil.bb.http.detection.BlackberryConnections;
import ar.com.lemil.bb.http.vo.HttpPing;
import ar.com.lemil.bb.http.vo.HttpRequest;
import ar.com.lemil.bb.utils.log.ILogger;
import ar.com.lemil.bb.utils.log.Logger;



public class HttpService {

	ILogger logger = null;
	String slog;
	
	String url;
	HttpRequest[] attachments;
	Hashtable parameters;
	boolean inDebugMode = false;
	

	public ILogger getScreen() {
		return logger;
	}
	public void setScreen(ILogger screen) {
		this.logger = screen;
	}
	
	public void setAttachments(HttpRequest[] attachments){
		this.attachments = attachments;
	}
	
	public void setUrl(String url){
		this.url = url;
	}
	
	public void setParameters(Hashtable parameters){
		this.parameters = parameters;
	}
	
	boolean sentResult = false;
	
	public boolean executePlan(Hashtable availableConnections) {
		
		String[] plan = BlackberryConnections.CONN_PLAN;
		
		boolean sent = false;
		Logger.getInstance().log("Execute plan. Steps:" + plan.length);
		
		if(plan.length  > 0){
			for(int i = 0; i < plan.length; i++){
				
				if(sent){
					break;
				}
				String plani = plan[i];
				if(availableConnections.containsKey(plani)){
					String v = (String)availableConnections.get(plani);
					String uid = plani;
					Logger.getInstance().log("Step: " + plani);
					String furl = url + v ;
					String response = tryChannel( uid,  furl,  parameters,  attachments);
					if(response != null){
						sent = parseResponse(response);
					}
				} else {
					Logger.getInstance().log("Skip Step: " + plani);
				}
			}
		} else {
			logger.status("No hay conexion disponible en este momento.");
		}
		
		return sent;

	}


	public String tryChannel(String uid, String url, Hashtable params, HttpRequest[] attachments)
	{
		String retval = null;
		try {
			retval = this.execute(url, params, attachments);
		} catch (Exception ex){		
			logger.status("Error al enviar por " + uid);
			Logger.getInstance().log(ex.getClass() + " " + ex.getMessage());
		}
		return retval;
	}
	
	private String execute(String url, Hashtable params, HttpRequest[] attachments) throws Exception 
	{
		logger.status("Conectando...");
		Logger.getInstance().log("url:" + url);

		HttpMultipartRequestUtils req = new HttpMultipartRequestUtils(url, params, attachments);

		req.setLogger(logger);
		
		logger.status("Enviando datos...");
		
		String response = req.sendMultipart();
		
		logger.status("Procesando...");
		
		if(response == null){
			Logger.getInstance().log("Response null");
			throw new RuntimeException("Servicio no disponible");
		}	
		
		Logger.getInstance().log(response);
		
		return response;
	}
	
	
	

	public boolean parseResponse(String xml)
	{
		try {
			int i = xml.indexOf("SUCCESS");
			//Logger.getInstance().log("index of success = " + i);
			//return true; 
			if(i != -1){
				return true;
			}
		} catch (Exception ex) {
			Logger.getInstance().log(ex.getClass() + " " + ex.getMessage());
		}
		return false;
	}
	


	
	
	/*public boolean parseResponse(String xml)
	{
	     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         DocumentBuilder builder;
         Document d;
		try {
			builder = factory.newDocumentBuilder();
			d = builder.parse( new ByteArrayInputStream(xml.getBytes()));
			NodeList nl = d.getElementsByTagName("status");
			if(nl.getLength() == 1){
				Node n = nl.item(0);
				NodeList nl2 = n.getChildNodes();
				Node n2 = n.getFirstChild();
				String status = n2.getNodeValue();
				if(status.equalsIgnoreCase("SUCCESS")){
					return true;
				} 
			}
		} catch (Exception ex) {
			screen.log(ex.getClass() + " " + ex.getMessage());
		}
		return false;
	}*/
	
	
	public Hashtable getAvailableConnections(){

		Logger.getInstance().log("Testing connections...\n");
		boolean sent = false;

		Hashtable suceecfullPing = new Hashtable();
		
		Hashtable actuveResults = new Hashtable();
		Hashtable activeUids = BlackberryConnections.getInstance().getFromActiveSB();	
		Logger.getInstance().log("Active Connections: " + activeUids.size() );
		Logger.getInstance().log("");
		
		long t = 1000;
		//Get Blackberry Connections
		Enumeration en = activeUids.keys();
		while(en.hasMoreElements())
		{
			String k = (String)en.nextElement();
			String v = (String)activeUids.get(k);
			
			Logger.getInstance().log("try:" + k + "=" + v);
			Logger.getInstance().log("------------------------");
			String furl = url + v;
			sent = pingChannel(k, furl,t);
			if(sent){
				suceecfullPing.put(k,v);
				this.sentResult = true;
			}
			actuveResults.put(k, "" + sent);
			Logger.getInstance().log("");
					
		}
		
		//Get API Hints
		Hashtable hintResults = new Hashtable();
		Hashtable hintUids = BlackberryConnections.getInstance().getFromHints();
		Logger.getInstance().log("Hint Connections: " + hintUids.size() );
		en = hintUids.keys();
		while(en.hasMoreElements())
		{
			String k = (String)en.nextElement();
			String v = (String)hintUids.get(k);
			Logger.getInstance().log("try:" + k + "=" + v);
			Logger.getInstance().log("------------------------");
			String furl = url + v;
			sent = pingChannel(k, furl,t);
			if(sent){
				suceecfullPing.put(k,v);
				this.sentResult = true;
			}
			hintResults.put(k, "" + sent);
			Logger.getInstance().log("");
		}
		return suceecfullPing;
	}
	
	private boolean pingChannel(String uid, String url, long timeout)
	{
		boolean retval = false;
		try {
			logger.status("Enviando datos via " + uid );
			
			HttpRequestUtils req = new HttpRequestUtils();
			HttpPing res = req.httpPing(url,timeout);
			
			Logger.getInstance().log("Ping " + res.toString());
			String s = res.isSuccess() ? "SUCCESS" : "FAIL";
			
			Logger.getInstance().log("Ping " + s);
			retval = res.isSuccess();
		} catch (Exception ex){		
			logger.status("Error al enviar por " + uid);
			Logger.getInstance().log(ex.getClass() + " " + ex.getMessage());
			retval = false;
		}
		return retval;
	}
	
}
	

